package com.csy.common.shiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csy.admin.entity.*;
import com.csy.admin.service.*;
import com.csy.admin.util.Md5HashUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 类名:自定义Realm
 * Created by CSY on 2018/9/5.
 */
public class CustomRealm extends AuthorizingRealm{

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.从主体传过来的认证信息中，获取用户名
        SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
        //2.从数据库中或缓存中获取用户角色信息
        List<SysRole> roleList = sysRoleService.findRolesByUserCode(sysUser.getUserCode());
        Set<String> roles = new HashSet<>();
        Set<String> permissions = new HashSet<>();
        //3.遍历角色获取权限，同时将角色和权限放到authorizationInfo中
        for(SysRole role : roleList){
            roles.add(role.getRoleName());
            List<SysMenu> menuList = sysMenuService.findPermissionByRole(role.getRoleId());
            for(SysMenu menu : menuList){
                if(menu.getPerms() != null) {
                    permissions.add(menu.getPerms());
                }
            }
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.从主体传过来的认证信息中，获取用户名
        String username = (String) authenticationToken.getPrincipal();
        //2.通过用户名到数据库中获取凭证
        SysUser sysUser = sysUserService.getOne(
                new QueryWrapper<SysUser>().eq("USER_CODE",username)
        );
        if(sysUser == null){
            throw new UnknownAccountException("账号或密码不正确");
        }
        String password = sysUser.getPassword();

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(sysUser,password,this.getName());
        //传入MD5加密盐
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(Md5HashUtil.SALT));
        return authenticationInfo;
    }
}
